package com.gbas.comu.util;

import javax.persistence.EntityManager;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class EntityManagerUtil {
    public static final ThreadLocal<EntityManager>
            ENTITY_MANAGERS = new ThreadLocal<EntityManager>();

    /**
     * Returns a fresh EntityManager
     */
    public static EntityManager getEntityManager() {
        return ENTITY_MANAGERS.get();
    }


    public static void makeFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        EntityManager em = EMF.get().createEntityManager();
        EntityManagerUtil.ENTITY_MANAGERS.set(em);
        filterChain.doFilter(servletRequest, servletResponse);
        EntityManagerUtil.ENTITY_MANAGERS.remove();
    }
}